package com.icarsaas.saas.master.service;

import com.icarsaas.saas.common.page.SoulPage;
import com.icarsaas.saas.master.model.MasterTenantDetail;
import com.icarsaas.saas.master.repository.MasterTenantDetailRepository;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

@Service
public class MasterTenantDetailService {
	@Autowired private MasterTenantDetailRepository masterTenantDetailRepository;
	
	public MasterTenantDetail get(String id, Long masterId) {
		MasterTenantDetail entity = null;
		if (StringUtils.isNotEmpty(id)) {
			entity = masterTenantDetailRepository.findById(id).orElse(null);
		} else if (masterId != null) {
			entity = masterTenantDetailRepository.findByMasterId(masterId);
		}
		return entity;
	}
	
	@Transactional(readOnly = false, value = "masterTransactionManager")
	public MasterTenantDetail save(MasterTenantDetail entity) {
		return masterTenantDetailRepository.save(entity);
	}
	
	@Transactional(readOnly = false, value = "masterTransactionManager")
	public void delete(String id) {
		masterTenantDetailRepository.deleteById(id);
	}

	public SoulPage<Map<String, Object>> listSoulData(SoulPage<Map<String, Object>> page, Map<String, Object> params) {
		StringBuffer sql = new StringBuffer("select t.* from master_tenant_detail t where 1=1 ");
		if (params != null && params.size() > 0) {
			for (String key : params.keySet()) {
				String value = (String) params.get(key);
				if (StringUtils.isNotEmpty(value)) sql.append(" and t." + key + " like '%" + value + "%'");
			}
		}
		SoulPage<Map<String, Object>> pageResult = masterTenantDetailRepository.findBySqlForSoul(page, sql.toString(), Map.class);
		return pageResult;
	}
}
